package com.kakame.codenews.front.article.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kakame.codenews.base.constant.SystemConstant;
import com.kakame.codenews.base.util.DateUtil;
import com.kakame.codenews.base.util.SessionUtil;
import com.kakame.codenews.base.web.controller.BaseController;
import com.kakame.codenews.base.web.entity.Page;
import com.kakame.codenews.base.web.entity.Result;
import com.kakame.codenews.base.web.fast.mapping.common.Article;
import com.kakame.codenews.base.web.fast.mapping.common.Dict;
import com.kakame.codenews.base.web.fast.mapping.nexus.ArticleComment;
import com.kakame.codenews.front.article.service.FrontArticleService;
import com.kakame.codenews.front.dict.service.FrontDictService;

/**
 * <pre>
 * <b>desc:</b> 前台文章相关控制器 
 * <b>auth:</b> ex-hejm
 * <b>date:</b> 2018年6月8日 下午1:37:47
 * </pre>
 */
@Controller
@RequestMapping("/front/article")
public class FrontArticleController extends BaseController {
	
	@Resource
	private FrontArticleService articleService;
	@Resource
	private FrontDictService dictService;
    
    /**
     * <pre>
     * <b>desc:</b> 文章首页 
     * <b>auth:</b> ex-hejm
     * <b>date:</b> 2018年6月12日 下午3:17:08
     * </pre>
     * @return
     */
    @RequestMapping("/index")
    public String index(ModelMap map, @RequestParam(defaultValue="1")Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize) {
    	
    	Page<Article> articlePage = articleService.page(pageNo, pageSize);
    	
    	map.put("articlePage", articlePage.getList());
    	map.put("menuCode", "SITE_HEADER_ARTICLE");
        return "front/article/index";
    }
    
    @RequestMapping("/load/{pageNo}")
    @ResponseBody
    public Page<Article> load(@PathVariable("pageNo") Integer pageNo) {
        Page<Article> articlePage = articleService.page(pageNo, SystemConstant.DEFAULT_PAGE_SIZE);
        return articlePage;
    }
    
    /**
     * 文章详情页面
     * @author 何家明 2018年7月4日 下午10:45:56
     * @param articleId
     * @return
     */
    @RequestMapping("/detail/{articleId}")
    public String detail(@PathVariable("articleId") String articleId, ModelMap map) {
    	Article article = articleService.get(articleId);
    	List<ArticleComment> comments = articleService.listChildComments(articleId);
    	map.put("article", article);
    	map.put("comments", comments);
    	map.put("menuCode", "SITE_HEADER_ARTICLE");
        return "front/article/detail";
    }
    
    /**
     * 获取文章具体评论下的回复
     * @author 何家明 2018年7月4日 下午10:45:56
     * @param commentId
     * @return
     */
    @RequestMapping("/comment/reply/{commentId}")
    @ResponseBody
    public Result listCommentReply(@PathVariable("commentId") String commentId) {
        Result result = null;
        try {
            List<ArticleComment> comments = articleService.listCommentRedirectReply(commentId);
            result = Result.create().setMsg("获取评论成功").setObject(comments).setStatus(SystemConstant.SUCCESS).build();
        } catch (Exception e) {
            result = Result.create().setMsg("获取评论失败").setStatus(SystemConstant.ERROR).build();
        }
        return result;
    }
    
    /**
     * 文章评论
     * @author 何家明 2018年7月4日 下午10:45:56
     * @param commentId
     * @return
     */
    @RequestMapping("/comment")
    public String comment(String articleId, String commentId, String comment, HttpSession session) {
        ArticleComment articleComment = ArticleComment.create()
                                                      .id(commentId)
                                                      .articleId(articleId)
                                                      .commentContent(comment)
                                                      .createUserId(SessionUtil.getCurrentUserId(session))
                                                      .createTime(DateUtil.getNow())
                                                      .build();
        articleService.insertComment(articleComment);
        return "redirect:detail/" + articleId + ".html";
    }

    /**
     * 文章删除
     * @author 何家明 2018年7月4日 下午10:45:56
     * @param articleId
     * @return
     */
    @RequestMapping("/delete/{articleId}")
    @ResponseBody
    public Result delete(@PathVariable("articleId") String articleId, ModelMap map) {
        Result result = null;
        int row = articleService.delete(articleId);
        if(row > 0) {
            result = Result.create().setMsg("删除成功").setStatus(SystemConstant.SUCCESS).build();
        } else {
            result = Result.create().setMsg("删除失败").setStatus(SystemConstant.ERROR).build();
        }
        return result;
    }
    
    @RequestMapping("/addPage")
    public String addPage(ModelMap map) {
    	commonInclude(map);
    	map.addAttribute("pType", "add");
        return "front/article/add";
    }
    
    /**
     * <pre>
     * <b>desc:</b> 跳转到修改页面 
     * <b>auth:</b> ex-hejm
     * <b>date:</b> 2018年7月19日 下午3:07:54
     * </pre>
     * @param articleId
     * @param map
     * @return
     */
    @RequestMapping("/edit/{articleId}")
    public String editPage(@PathVariable("articleId") String articleId, ModelMap map) {
        commonInclude(map);
        Article article = articleService.get(articleId);
        map.addAttribute("article", article);
        map.addAttribute("pType", "edit");
        return "front/article/add";
    }

    private void commonInclude(ModelMap map) {
        List<Dict> dicts = dictService.list(Dict.create().dictGrandpaCode("COMMON_ARTICLE_CATEGORY").build());
        
        List<Dict> parentList = new ArrayList<Dict>();
        for (Dict dict : dicts) {
            if(StringUtils.equals(dict.getDictGrandpaCode(), dict.getDictParentCode())) {
                parentList.add(dict);
            }
        }
        for (Dict pDict : parentList) {
            List<Dict> childList = new ArrayList<Dict>();
            for (Dict dict : dicts) {
                if(StringUtils.equals(dict.getDictParentCode(), pDict.getDictCode())) {
                    childList.add(dict);
                }
            }
            pDict.setChildList(childList);
        }
        map.put("articleCategory", parentList);
        map.put("menuCode", "SITE_HEADER_ARTICLE");
    }
    
    /**
     * 新增文章
     * @author 何家明 2018年7月4日 下午9:30:41
     * @param article
     * @return
     */
    @RequestMapping("/add")
    public String add(Article article, HttpSession session, ModelMap map) {
    	article.setCreateUserId(SessionUtil.getCurrentUserId(session));
    	articleService.add(article);
    	map.put("menuCode", "SITE_HEADER_ARTICLE");
    	return "redirect:index.html";
    }
    
    /**
     * 修改文章
     * @author 何家明 2018年7月4日 下午9:30:41
     * @param article
     * @return
     */
    @RequestMapping("/edit")
    public String edit(Article article, HttpSession session, ModelMap map) {
        article.setUpdateUserId(SessionUtil.getCurrentUserId(session));
        articleService.update(article);
        map.put("menuCode", "SITE_HEADER_ARTICLE");
        return "redirect:index.html";
    }
}
